package com.hex.es.service.impl;

import com.github.vanroy.springdata.jest.JestElasticsearchTemplate;
import com.github.vanroy.springdata.jest.mapper.JestResultsExtractor;
import com.google.gson.JsonObject;
import com.hex.es.annotation.EsBuildParamTypeInfo;
import com.hex.es.service.ReturnSearchInterface;
import io.searchbox.core.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * @description: Integer返回类型处理类
 * @author: Hex
 * @date: 2019/11/13 16:29
 */
@Slf4j
@Service
public class ReturnIntegerImpl implements ReturnSearchInterface {

    @Resource
    private JestElasticsearchTemplate jestElasticsearchTemplate;

    @Resource
    private ReturnListImpl returnList;

    @Override
    public Object search(Method method, EsBuildParamTypeInfo esBuildParamTypeInfo, SearchQuery searchQuery) {
        returnList.search(method,esBuildParamTypeInfo,searchQuery);
        JsonObject jsonObject = jestElasticsearchTemplate.query(searchQuery, new JestResultsExtractor<JsonObject>() {
            @Override
            public JsonObject extract(SearchResult response) {
                return response.getJsonObject();
            }
        });
        return jsonObject.getAsJsonObject("hits").getAsJsonPrimitive("total").getAsInt();
    }

    @Override
    public Boolean check(Method method, EsBuildParamTypeInfo esBuildParamTypeInfo) {
        return Integer.class.equals(method.getReturnType());
    }

    @Override
    public int getOrder() {
        return 5;
    }
}
